package a07_二叉树;

/**
 * <p>
 * a26_二叉树的最近公共祖先复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/4/17
 */
public class a26_二叉树的最近公共祖先复习2 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }

        if (root == p || root == q) {
            return root;
        }

        TreeNode leftReturn = lowestCommonAncestor(root.left, p, q);
        TreeNode rightReturn = lowestCommonAncestor(root.right, p, q);

        if(leftReturn != null && rightReturn != null){//那么root就是公共祖先
            return root;
        }else if(leftReturn != null && rightReturn == null){
            return leftReturn;
        }else if(leftReturn == null && rightReturn != null){
            return rightReturn;
        }else {
            return null;
        }
    }
}
